﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.DependencyInjection;
using StyleMVVM.Logging;

namespace StyleMVVM.View.Impl
{
	public sealed class ViewBinderService : IViewBinderService
	{
		private static string supplemental = typeof(ViewBinderService).FullName;
		private IEnumerable<IViewBinder> viewBinders;

		public static void RegisterExport(IDependencyInjectionContainer container)
		{
			container.Register(typeof(ViewBinderService))
			         .As(typeof(IViewBinderService))
			         .ImportMethod("ImportDependencies")
			         .AndShared();
		}

		public void ImportDependencies(IEnumerable<IViewBinder> viewBinders)
		{
			this.viewBinders = viewBinders;
		}

		public void Bind(object view, object navigationParameter)
		{
			foreach (IViewBinder viewBinder in viewBinders)
			{
				try
				{
					viewBinder.Bind(view, navigationParameter);
				}
				catch (Exception exp)
				{
					Logger.Error("Exception thrown while executing view binder: " + viewBinder.GetType().FullName, supplemental, exp);
				}
			}
		}
	}
}